package com.xdap.common.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256 {

    public static String sha256(final String contents) {
        String encryptedContents = "";
        try
        {
            MessageDigest messageDigest = null;
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.reset();
            messageDigest.update(contents.getBytes("UTF-8"));
            encryptedContents = byteToString(messageDigest.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
            System.exit(-1);
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        return encryptedContents;

    }
    public static String byteToString(byte[] bByte) {
        StringBuffer encrytStrBuf = new StringBuffer();

        for (int i = 0; i < bByte.length; i++)
        {
            if (Integer.toHexString(0xFF & bByte[i]).length() == 1)
                encrytStrBuf.append("0").append(Integer.toHexString(0xFF & bByte[i]));
            else
            {
                encrytStrBuf.append(Integer.toHexString(0xFF & bByte[i]));
            }
        }
        return encrytStrBuf.toString().toUpperCase();
    }

    public static String toSHA256(String username, String password){
        String encryptStr=username.toUpperCase()+"+"+ SHA256.sha256(password);
        encryptStr= SHA256.sha256(encryptStr);
        return encryptStr;
    }
    public static void main(String[] args) {
        //AA8D8498233A8F4A7536CBD4AED921E4249847F1557D59FC4DDF05FE7514857F
        System.out.println(sha256("welcome1"));
    }


}
